import Qt 4.7
import QtWebKit 1.0
import "OAuth.js" as OAuthLogic

	 
Item{
    id: root
    width: 1024
    height: 768
    property string username: ''
    property string password: ''
    property string token: ""
    property string secret:""
	property string user_id:""
    function beginAuthentication(){
        step = 1;
        stepOne();
    }
    signal authenticationCompleted();
	signal authenticationFail;
    //property var credentials: new Object
    property int step: 0
    function nextStep(){
        if(step == 1)
            stepOne();
        else if(step == 2)
            stepTwo();
        else if(step == 3)
            stepThree();
        return;
    }
    function stepOne(){
        var xhr = OAuthLogic.createOAuthHeader("POST", "http://api.t.sina.com.cn/oauth/request_token", [["oauth_callback","oob"]]);
        xhr.onreadystatechange = function() { 
            if (xhr.readyState == XMLHttpRequest.DONE) {
                var response = xhr.responseText.split('&');
                if(response.length != 3) {
					//console.log("response format error,callback fail?\n")                    
					if(response.length <2 ) {
						authenticationFail();
						return;
					}
				}
				
                token = response[0].split('=')[1];
                secret = response[1].split('=')[1];
                if(response.length ==3 && response[2].split('=')[1] != 'true')
                    console.log("Error: " + response[2]);
                step = 2;
                webItem.url = "http://api.t.sina.com.cn/oauth/authorize?oauth_token="+token;				
            }
        }
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Accept-Language", "en");
        xhr.send();
    }
    function stepTwo(){
        step = 3;
        var page = webItem.html;
        //console.log("Step2\n" + page);
        webItem.evaluateJavaScript("document.getElementById(\"userId\").value = \"" + username + "\";");
        webItem.evaluateJavaScript("document.getElementById(\"passwd\").value = \"" + password + "\";");
        webItem.evaluateJavaScript("authZForm.submit();")
    }
    function stepThree(){		
        //console.log("Step3\n" + webItem.html);
		if(webItem.evaluateJavaScript("document.body.innerHTML.search('获取到授权码：')")<=0){
			console.log("password error\n");
			authenticationFail();
			return;
		}
        var pin =  webItem.evaluateJavaScript("document.body.innerHTML.substr('获取到授权码：'.length+document.body.innerHTML.search('获取到授权码：'),6)");
		console.log("pin=" + pin+"\n");
        var xhr = OAuthLogic.createOAuthHeader("POST", "http://api.t.sina.com.cn/oauth/access_token", [["oauth_verifier",pin]], {"token":token,"secret":secret});
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                //console.log('STEP 3\n'+xhr.status+'\n'+xhr.getAllResponseHeaders()+'\n'+xhr.responseText+xhr.responseXML);
                var response = xhr.responseText.split('&');
                if(response.length <3){
					authenticationFail();
                    return;
				}
                token = response[0].split('=')[1];
                secret = response[1].split('=')[1];
                user_id = response[2].split('=')[1];
                step = 0;
                authorized = true;
				var db = openDatabaseSync("tsinaclient", "1.0", "新浪微博数据库", 1000000);
					db.transaction(
					function(tx) {
                     tx.executeSql('delete from passwds where username=?',[username]);
                     tx.executeSql('INSERT INTO passwds VALUES(?, ?,?,?,?)', [ username, password,token,secret,user_id ]);
                 });
                authenticationCompleted();				
            }
        }
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Accept-Language", "en");
        xhr.send();
    }
    property bool authorized: false
    WebView{
        id: webItem
        url: "about:blank"
        opacity: 0
        onLoadFinished: nextStep();
        anchors.fill: parent;
    }
}
